<?php
// 中介者模式
// 需要互相通信的类，交给中介者来进行通信

abstract class Colleague
{
	protected $mediator;
	abstract public function sendMsg($to, $msg);
	abstract public function receiveMsg($msg);
	public function setMediator(Mediator $mediator)
	{
		$this->mediator = $mediator;
	}
}

class ColleagueA extends Colleague
{
	public function sendMsg($to, $msg)
	{
		$this->mediator->operation($to, $msg);
	}
}

class ColleagueB extends Colleague
{

}

abstract class Mediator
{
	abstract public function operation($to, $msg);
	abstract public function register($id, Colleague $colleague);
}

class MyMediator extends Mediator
{
	protected static $colleagues;

	function __construct()
	{
		if (!isset(self::$colleagues)) {
			self::$colleagues = [];
		}
	}

	public function operation($id, $msg)
	{
		if (!array_key_exists($id, self::$colleagues)) {
			return;
		}
		$colleague = self::$colleagues[$id];
		$colleague->receiveMsg($msg);
	}

	public function register($id, Colleague $colleague)
	{
		if (!in_array($colleague, self::$colleagues)) {
			self::$colleagues[$id] = $colleague;
		}
		$colleague->setMediator($this)
	}
}

$colleagueA = new ColleagueA;
$colleagueB = new ColleagueB;
$mediator = new MyMediator;
$mediator->register(1, $colleagueA);
$mediator->register(2, $colleagueB);
$colleague->sendMsg(2, 'dfdf');